//
//  HomeViewController.swift
//  weile
//
//  Created by LKM on 16/10/9.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit

class HomeViewController: BaseViewController {
    
    public static var SelectIndex :Int = 0;//开放给外面用来跳转的
    
    @IBOutlet weak var searchBox: UIView!
    @IBOutlet weak var lbl_search: UILabel!
    @IBOutlet weak var contentWrapView: UIView!
    // 标签
    weak var titlesView = UIView()
    //标签下 底部颜色条指示器
    weak var indicatorView = UIView()
    ///标签 当前选中的按钮
    weak var selectedButton = UIButton()
    
    
    weak var contentView = UIScrollView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        var index = 0;
        //添加视图
        for i in [("582","轻钢别墅"),("584","集装箱"),("582","钢结构"),("582","组合房")] {
            var vc:BaseViewController!
            if(index == 0 || index == 1){
              vc = ActivityRequest.getProductsViewController(mainId:i.0)
            }else{
                vc=ActivityRequest.getTipsViewController("- 等待开放 -")
            }
            vc.isShowContentBg = false;
            vc.view.backgroundColor = UIColor.clear
            vc.title = i.1
//            vc.type = 2;
            self.addChildViewController(vc)
            
            index += 1;
        }
        
        //设置顶部标签栏
        self.setupTitlesView()
        // 底部的scrollview
        self.setupContentView()
        
        
        ViewHelp.setOnClickListening(searchBox, self, #selector(onSearchBoxClick))
        searchBox.layer.cornerRadius = 15;// lbl_search.height/2;
//        searchBox.backgroundColor = UIColor.red
        //lbl_search.layoutMargins = UIEdgeInsetsMake(0, 24, 0, 4)
        
        
    }
    
    func onSearchBoxClick(){
        ActivityRequest.goSearchViewController(self.navigationController!)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    override func viewWillDisappear(_ animated: Bool) {
        HomeViewController.SelectIndex=0;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    let kTitlesViewH :CGFloat = 30
    //顶部
    let kTitlesViewY :CGFloat = 0;//20 因为xib了
    /// 顶部标签栏
    func setupTitlesView() {
        
        let kIndicatorViewH :CGFloat = 2.0
        /// 屏幕的宽
        let SCREENW = UIScreen.main.bounds.size.width
        
//        let topview = UIView()
//        topview.frame = CGRect(x: 0, y: 0, width: SCREENW, height: kTitlesViewY)
//        topview.backgroundColor = UIColor.clear
//        view.addSubview(topview)

        
        // 顶部背景
        let bgView = line_bottom_uiview()
        bgView.frame = CGRect(x: 0, y: kTitlesViewY, width: SCREENW, height: kTitlesViewH)
//        bgView.backgroundColor=UIColor.red
        contentWrapView.addSubview(bgView)
        // 标签
        let titlesView = UIView()
        titlesView.backgroundColor = UIColor.clear
        titlesView.frame = CGRect(x: 0, y: 0, width: SCREENW , height: kTitlesViewH)
        bgView.addSubview(titlesView)
        self.titlesView = titlesView
        
        
//        // 选择按钮
//        let arrowButton = UIButton()
//        arrowButton.frame = CGRect(x: SCREENW - kTitlesViewH, y: 0, width: kTitlesViewH, height: kTitlesViewH)
//        arrowButton.setImage(UIImage(named: "arrow_index_down_8x4_"), for: UIControlState())
//        arrowButton.addTarget(self, action: #selector(arrowButtonClick(_:)), for: .touchUpInside)
//        arrowButton.backgroundColor = YMGlobalColor()
//        bgView.addSubview(arrowButton)
        
        //内部子标签
        let count = childViewControllers.count
        let width = titlesView.width / CGFloat(count)
        let height = titlesView.height
        
        //底部颜色指示器
        let indicatorView = UIView()
//        67, 153, 165
        indicatorView.backgroundColor = UIColor(red: 67/255, green: 153/255, blue: 165/255, alpha: 1)//R.colors.base_color
        indicatorView.height = kTitlesViewH//kIndicatorViewH
        indicatorView.width = width
        indicatorView.y = 0//kTitlesViewH - kIndicatorViewH
        indicatorView.tag = -1
        self.indicatorView = indicatorView
        //底部指示器
        titlesView.addSubview(indicatorView)
        
        for index in 0..<count {
            let button = UIButton()
            button.height = height
            button.width = width
            button.x = CGFloat(index) * width
            button.tag = index
            let vc = childViewControllers[index]
            button.titleLabel!.font = UIFont.systemFont(ofSize: 14)
            button.setTitle(vc.title!, for: UIControlState())
            button.setTitleColor(R.colors._535353, for: UIControlState())
            button.setTitleColor(UIColor.white, for: .disabled)
            button.addTarget(self, action: #selector(titlesClick(_:)), for: .touchUpInside)
            titlesView.addSubview(button)
            //默认点击 默认要的那个
            if index == HomeViewController.SelectIndex {
                button.isEnabled = false
                selectedButton = button
                //让按钮内部的Label根据文字来计算内容
//                button.titleLabel?.sizeToFit()
//                indicatorView.width = button.titleLabel!.width
                indicatorView.centerX = button.centerX
                
                Handler.post {
                    FXM.D("貌似第一个会先加载  然后再跳到指定的")
                    //等待setupContentView（）；
                    self.titlesClick(button)
                }
            }
        }
        
    }

    /// 标签上的按钮点击
    func titlesClick(_ button: UIButton) {
        // 修改按钮状态
        selectedButton!.isEnabled = true
        button.isEnabled = false
        selectedButton = button
        // 让标签执行动画
        UIView.animate(withDuration: kAnimationDuration, animations: {
//            self.indicatorView!.width = self.selectedButton!.titleLabel!.width
            self.indicatorView!.centerX = self.selectedButton!.centerX
        })
        //滚动,切换子控制器
        var offset = contentView!.contentOffset
        offset.x = CGFloat(button.tag) * contentView!.width
        contentView!.setContentOffset(offset, animated: true)
    }

    
    /// 底部的scrollview
    func setupContentView() {
        //不要自动调整inset
        automaticallyAdjustsScrollViewInsets = false
        
        let contentView = UIScrollView()
        contentView.frame = view.bounds
        contentView.y=kTitlesViewH+kTitlesViewY;
        contentView.delegate = self
        contentView.contentSize = CGSize(width: contentView.width * CGFloat(childViewControllers.count), height: 0)
        contentView.isPagingEnabled = true//UIScrollView会被分割成多个独立页面，用户的滚动体验则变成了页面翻转
        contentWrapView.insertSubview(contentView, at: 0)
        self.contentView = contentView
        //添加第一个控制器的view
        scrollViewDidEndScrollingAnimation(contentView)
    }

    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension HomeViewController: UIScrollViewDelegate {
    // MARK: - UIScrollViewDelegate
    //好像这里系统不会自动调用，打log看到触发都是我代码调用的
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        // 添加子控制器的 view
        // 当前索引
        let index = Int(scrollView.contentOffset.x / scrollView.width)
        // 取出子控制器
        let vc = childViewControllers[index]
        vc.view.x = scrollView.contentOffset.x
        vc.view.y = 0 // 设置控制器的y值为0(默认为20)
        //设置控制器的view的height值为整个屏幕的高度（默认是比屏幕少20）
        vc.view.height = scrollView.height
        scrollView.addSubview(vc.view)
        FXM.D("=====\(self)这里有疑问 为什么一直addSubview 难道这是isPagingEnabled的神奇效果？")
    }
    
    //scrollview 先是执行 停止拖住的代理 然后在执行减速停止的代理.这个是减速
    //为的是放手就能看到内容，且减速意味着不会滚到下个index去
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        LKMLog("====scrollViewDidEndDecelerating")
        
        scrollViewDidEndScrollingAnimation(scrollView)
        // 当前索引
        let index = Int(scrollView.contentOffset.x / scrollView.width)
        // 点击 Button +1 是因为背景滑动色块
        let button = titlesView!.subviews[index+1] as! UIButton
        titlesClick(button)
    }
}
